package a09_JUC;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * @Author quan
 * @Description Callable接口实现数字的累加
 * @Date 2023/5/15 16:00
 */
public class a01_Callable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1、定义一个线程的任务，重写Callable接口中的call方法
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                //2、对变量进行累加
                int sum = 0;
                for (int i = 0; i < 5; i++) {
                    sum = sum + i;
                }
                //3、返回结果
                return sum;
            }
        };
        //4、通过FutureTask类来创建一个对象，这个对象持有callable
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        //5、创建线程并指定任务
        Thread thread = new Thread(futureTask);
        //6、启动线程，让线程执行定义好的任务
        thread.start();
        //7、获取线程执行的结果
        System.out.println("等待结果...");
        Integer result = futureTask.get();
        //8、打印结果
        System.out.println(result);
    }
}
